package room

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
	"github.com/sirupsen/logrus"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *RoomService) checkLeaveRoomReqData(data common.SFULeaveRoomReqData) error {
	// Check if room ID is provided
	if data.RoomId == "" {
		return errors.New("room ID is required in leave room request")
	}
	// Check if user ID is provided
	if data.UserId == "" {
		return errors.New("user ID is required in leave room request")
	}
	// Check if room exists
	if !s.roomMgr.RoomExists(data.RoomId) {
		return errors.New("room does not exist")
	}
	// Check if user is in the room
	if !s.roomMgr.UserExists(data.RoomId, data.UserId) {
		return errors.New("user is not in the room")
	}
	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *RoomService) sendLeaveRoomResponse(rid string, code int, msg string, connId string,
	data common.SFULeaveRoomReqData) {
	resMsg := common.Message{
		Cmd: common.SFU_LEAVE_ROOM_RES,
		Rid: rid,
		Data: common.ResMsgData{
			Code: code,
			Msg:  msg,
			Data: common.SFULeaveRoomResData{
				RoomId: data.RoomId,
				UserId: data.UserId,
			},
		},
	}
	s.dispatcher.Dispatch(resMsg, s.serviceInfo, common.AccessServiceInfo, connId)
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *RoomService) handleLeaveRoomReq(msg common.Message, from common.ServiceInfo,
	connId string) error {
	LOG().WithFields(logrus.Fields{
		"msg":    common.ToJson(msg),
		"from":   from,
		"connId": connId,
	}).Info("Handling leave room request")

	var data common.SFULeaveRoomReqData
	if err := mapstructure.Decode(msg.Data, &data); err != nil {
		return errors.New("failed to decode leave room request data: " + err.Error())
	}

	if data.RoomId == "" || data.UserId == "" {
		LOG(msg.Rid).Error("room ID or user ID is empty in leave room request")
		s.sendLeaveRoomResponse(msg.Rid, 1, "room ID or user ID is empty", connId, data)
		return nil
	}

	s.roomMgr.RemoveUserFromRoom(msg.Rid, data.RoomId, data.UserId)

	s.sendLeaveRoomResponse(msg.Rid, 0, "success", connId, data)

	return nil
}
